package com.example.myapplication.Student;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.example.myapplication.Adapter.SignInListAdapter;
import com.example.myapplication.Data.CourseData;
import com.example.myapplication.Data.CourseDetailData;
import com.example.myapplication.Data.SignInList;
import com.example.myapplication.Data.SignInListData;
import com.example.myapplication.Data.UserData;
import com.example.myapplication.R;
import com.example.myapplication.http.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class SignInAlreadyFragment extends Fragment {

    private JsonObject jsonObject;
    private SignInListData signInListData;//用于接收请求数据
    private SignInListAdapter adapter;
    private ListView lvCourseList;//适配器显示视图
    private List<SignInList> signInList;

    private UserData userData;
    private CourseDetailData courseDetailData;

    private final Gson gson = new Gson();
    //请求数据
    private int code;// 响应码
    private String msg;// 提示信息
    private Object data;// 实际数据

    protected View mView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }
    private void initView() {
        userData = (UserData) getActivity().getIntent().getSerializableExtra("userData");
        courseDetailData =(CourseDetailData) getActivity().getIntent().getSerializableExtra("courseDetailData");
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_sign_in_already, container, false);
            lvCourseList = mView.findViewById(R.id.list_courses);
            get();
        }

        // 如果 mView 不为空，表示视图已经创建
        return mView;
    }

    private void get(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/sign/course/student/signList" +
                    "?courseId=" + courseDetailData.getId() +
                    "&status=1" +
                    "&userId=" + userData.getId();

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());

            // 获取响应的数据
            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();

            handleResponse();
        }
    };

    private void handleResponse() {
        if (code == 200) {
            // 请求成功
            if (data != null) {

                jsonObject = gson.toJsonTree(data).getAsJsonObject();
                signInListData = gson.fromJson(jsonObject, SignInListData.class);
                signInList = signInListData.getRecords();

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                    }
                });

            } else {
                Log.d("返回空值", "data=null");
                Refresh();
            }
        } else {
            // 请求失败
            if (msg != null) {
                Log.d("请求失败", msg);
            }
        }
    }
    public void initData() {
        lvCourseList=(ListView)getActivity().findViewById(R.id.sign_in_already);

        adapter = new SignInListAdapter( getActivity(),
                R.layout.list_item_sign_in, signInList);
        lvCourseList.setAdapter(adapter);
        Refresh();
    }
    //刷新
    public void Refresh() {
        //刷新列表
        SwipeRefreshLayout swipeRefreshLayout = getActivity().findViewById(R.id.swipeRefreshLayout_sign_in_aleady);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                get();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }
}